package com.example.demo.ctrl;

import com.example.demo.pool.MysqlPool;
import com.example.demo.util.MysqlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.CountDownLatch;

/**
 * @author maxf
 * @version 1.0
 * @ClassName CoonCtrl
 * @Description
 * @date 2019/2/14 14:53
 */
@RestController
public class CoonCtrl {
    final static String SQL = "INSERT INTO t_user(name) VALUES ('2')";

    @Autowired
    private MysqlPool mysqlPool;



    @GetMapping("/a/{time}")
    public long getCoon(@PathVariable int time) {
        System.out.println(time + "请求连接，请求线程" + Thread.currentThread().getName());
        long count = 0;
        for (int i = 0; i < time; i++) {
            Connection conn = MysqlUtils.createCoon();
            business(conn, SQL);
            System.out.println("插入数据成功");
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    private CountDownLatch countDownLatch = new CountDownLatch(15);
    @GetMapping("/{time}")
    public long getCoonPool(@PathVariable int time) {
        long count = 0;
        System.out.println(time + "请求连接，请求线程" + Thread.currentThread().getName());
        //多线程执行
        new Thread(() -> {
            countDownLatch.countDown();//线程就绪，减1
            try {
                countDownLatch.await();//如果大于0，还有线程未就绪,阻塞线程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 0; i < time; i++) {
                Connection conn = mysqlPool.getCoon();
                int business = business(conn, SQL);
                if (business == 1) {
                    System.out.println("插入数据成功" + i);
                }
                mysqlPool.release(conn);
            }
        }).start();

//        for (int i = 0; i < time; i++) {
//            Connection conn = mysqlPool.getCoon();
//            business(conn, SQL);
//            System.out.println("插入数据成功");
//            mysqlPool.release(conn);
//        }
        return count;
    }

    private int business(Connection conn, String sql) {
        try {
            Statement sm = conn.createStatement();
            return sm.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
